package cn.wolfcode.wms.interceptor;

import cn.wolfcode.wms.domain.Employee;
import cn.wolfcode.wms.util.ExpressionFactory;
import cn.wolfcode.wms.util.RequirePermission;
import cn.wolfcode.wms.util.UserContext;
import org.springframework.stereotype.Service;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.List;

@Service
public class SecurtityInterceptor extends HandlerInterceptorAdapter{
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //超管放行
        List<String> exps = UserContext.getCurrentPermission();
        Employee e = UserContext.getCurrentUser();
        if (e.isAdmin()) {
            return true;
        }

        //不需要权限放行
        HandlerMethod hm = (HandlerMethod) handler;
        Method m = hm.getMethod();
        System.out.println(m);
        if (!m.isAnnotationPresent(RequirePermission.class)) {
            return true;
        }
        //验证权限
        String exp = ExpressionFactory.buildExpression(m);


        if (exps.contains(exp)) {
            return  true;

        }
        request.getRequestDispatcher("/WEB-INF/views/nopermission.jsp").forward(request,response);

        return false;
    }
}
